#include <54func.h>
#define NUM 10000000
//引入互斥锁来保证主线程与子线程对共享资源的访问
typedef struct shareRes_s{
    int val;//主线程与子线程共享变量
    pthread_mutex_t mutex;//锁
}shareRes_t;
void *threadFunc(void *arg)
{
    shareRes_t *pshareRes = (shareRes_t *)arg;
    for(int i=0;i<NUM;i++)
    {
        //上锁
        pthread_mutex_lock(&pshareRes->mutex);
        ++pshareRes->val;
        pthread_mutex_unlock(&pshareRes->mutex);//解锁
    }
    pthread_exit(NULL);//进程退出
}
int main()
{
    shareRes_t shareRes;
    //初始化
    shareRes.val = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);//创建锁，并初始化一把未上锁的锁
    
    pthread_t tid;
    pthread_create(&tid,NULL,threadFunc,&shareRes);
    for(int i=0;i<NUM;i++)
    {
        pthread_mutex_lock(&shareRes.mutex);//上锁
        shareRes.val++;
        pthread_mutex_unlock(&shareRes.mutex);//解锁
    }
    pthread_join(tid,NULL);//回收子线程资源
    printf("val = %d\n",shareRes.val);
    return 0;
}
